import 'dart:async';

import 'package:base_project/common/event/http_error_event.dart';
import 'package:base_project/common/event/index.dart';
import 'package:base_project/common/net/code.dart';
import 'package:base_project/common/utils/common_utils.dart';
import 'package:base_project/common/utils/log_utils.dart';
import 'package:base_project/model/User.dart';
import 'package:base_project/page/layout/layout_binding.dart';
import 'package:base_project/page/splash/splash_binding.dart';
import 'package:base_project/page/splash/splash_view.dart';
import 'package:base_project/res/colors.dart';
import 'package:base_project/res/localization/app_localizations_delegate.dart';
import 'package:base_project/res/localization/default_localizations.dart';
import 'package:base_project/route/routes.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';


import 'global/global_controller.dart';
import 'page/layout/layout_test_page.dart';


///Application
class FlutterApp extends StatefulWidget {
  @override
  _FlutterAppState createState() => _FlutterAppState();
}

class _FlutterAppState extends State<FlutterApp>
    with HttpErrorListener {
  @override
  void initState() {
    super.initState();
    LogD("应用初始化 initState >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

    var controller = GetInstance().find<GlobalController>();
    var state = controller.state;
    state.platformLocale = WidgetsBinding.instance.platformDispatcher.locale;
    state.userInfo = User.empty();
    state.login = false;
    state.themeData = CommonUtils.getThemeData(ColorStyle.primarySwatch);

    ///TODO:  locale: Locale('zh', 'CH')) ？？？
    state.locale = Locale('zh', 'CH');
  }

  @override
  Widget build(BuildContext context) {
    LogD("应用初始化 build >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    return GetBuilder<GlobalController>(
        builder: (globalController) =>

            ///屏幕适配插件初始化
            ScreenUtilInit(
                designSize: const Size(1080, 1920),
                builder: (_, child) => new GetMaterialApp(
                      ///路由列表
                      getPages: AppRoutes.routerPages,

                      ///指定启动页面
                      initialBinding: LayoutBinding(),
                      home: MyWidget(),

                      ///多语言实现代理
                      localizationsDelegates: [
                        GlobalMaterialLocalizations.delegate,
                        GlobalCupertinoLocalizations.delegate,
                        GlobalWidgetsLocalizations.delegate,
                        AppLocalizationsDelegate.delegate,
                      ],
                      supportedLocales: [
                        globalController.state.locale ??
                            globalController.state.platformLocale!
                      ],

                      ///语言
                      locale: globalController.state.locale,

                      ///主题
                      theme: globalController.state.themeData,

                      /// 注册 AuthMiddleware
                      defaultTransition: Transition.fade,
                      opaqueRoute: Get.isOpaqueRouteDefault,
                      popGesture: Get.isPopGestureEnable,
                      enableLog: Get.isLogEnable,
                      logWriterCallback: localLogWriter,
                      routingCallback: (Routing? routing) => print(routing),
                      // 注册 AuthMiddleware
                      // defaultMiddlewares: [AuthMiddleware()],

                      navigatorKey: Get.key,
                      navigatorObservers: [],
                    )));
  }

  void localLogWriter(String text, {bool isError = false}) {
    // pass the message to your favourite logging package here
    // please note that even if enableLog: false log messages will be pushed in this callback
    // you get check the flag if you want through GetConfig.isLogEnable
  }
}

mixin HttpErrorListener on State<FlutterApp> {
  StreamSubscription? stream;

  // GlobalKey<NavigatorState> navKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    LogD("应用初始化 HttpErrorListener initState >>>>>>>>>>>>>>>>>");

    ///Stream演示event bus
    stream = eventBus.on<HttpErrorEvent>().listen((event) {
      errorHandleFunction(event.code, event.message);
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (stream != null) {
      stream!.cancel();
      stream = null;
    }
  }

  ///TODO: 公共网络错误提醒
  ///网络错误提醒
  errorHandleFunction(int? code, message) {
    var context = Get.key.currentContext!;
    switch (code) {
      case Code.NETWORK_ERROR:
        showToast(AppLocalizations.i18n(context)!.network_error);
        break;
      case Code.NETWORK_TIMEOUT:
        //超时
        showToast(AppLocalizations.i18n(context)!.network_error_timeout);
        break;
      default:
        showToast(AppLocalizations.i18n(context)!.network_error_unknown +
            " " +
            message);
        break;
    }
  }

  showToast(String message) {
    Fluttertoast.showToast(
        msg: message,
        gravity: ToastGravity.CENTER,
        toastLength: Toast.LENGTH_LONG);
  }
}
